package com.xbongbong.paas.help;/*/*/

import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasCoUserEntity;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.OptionalRangeEnum;
import com.xbongbong.paas.enums.RelatedPersonnelEnum;
import com.xbongbong.paas.enums.VisibleTypeEnum;
import com.xbongbong.paas.field.VisibleRulePoJo;
import com.xbongbong.paas.model.PaasCoUserModel;
import com.xbongbong.paas.pojo.dto.CoUserListDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.RoleEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.RoleEnum;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.RoleModel;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 处理解释需要用的helper
 * @author 魏荣杰
 * @date 2019/4/11 16:19
 * @since v1.0
 * @version v1.0
 */
@Component
public class FormDataFormExplainHelper {

    private static final Logger LOG = LoggerFactory.getLogger(FormDataFormExplainHelper.class);

    @Resource
    private RoleModel roleModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private UserModel userModel;
    @Resource
    private BusinessUserTeamHelp businessUserTeamHelp;
    @Resource
    private PaasCoUserModel paasCoUserModel;

    /**
     * 处理部门、角色、用户
     * @param list 设置的选项
     * @return
     * @throws XbbException
     */
    public List<OptionalRangeEntity> handleOptionalRangeList(List<OptionalRangeEntity> list, String corpid , Map<String, UserEntity> userMap,
                                                             Map<String, DepartmentEntity> departmentMap, Map<String, RoleEntity> roleMap) throws XbbException{
        List<OptionalRangeEntity> rangeList = new ArrayList<>();

        try {
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (OptionalRangeEntity range: list) {
                params.clear();
                params.put(StringConstant.CORPID, corpid);
                params.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
                if (OptionalRangeEnum.USER.getValue().equals(range.getProperty())) {
                    getUserMap(userMap, params);
                    UserEntity userEntity = getUserName(range.getId(), userMap);
                    if(userEntity != null) {
                        range.setName(userEntity.getName());
                    }
                }else if (OptionalRangeEnum.DEPT.getValue().equals(range.getProperty())) {
                    getDepartmentMap(departmentMap, params);
                    DepartmentEntity departmentEntity = getDepartmentName(range.getId(), departmentMap);
                    if(departmentEntity != null) {
                        range.setName(departmentEntity.getName());
                    }
                }else if (OptionalRangeEnum.ROLE.getValue().equals(range.getProperty())){
                    getRoleMap(roleMap, params);
                    RoleEntity roleEntity = getRoleName(range.getId(), roleMap);
                    if(roleEntity != null) {
                        range.setName(roleEntity.getRoleName());
                    }
                }
                rangeList.add(range);
            }
        } catch (Exception e) {
            LOG.error("获取部门、角色、用户等名称报错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return rangeList;
    }

    public void getRoleMap(Map<String, RoleEntity> roleMap, Map<String, Object> params) throws XbbException{
        if(roleMap.isEmpty()){
            List<RoleEntity> roleList = roleModel.findEntitys(params);
            if(roleList == null){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.ROLE_NOT_EXIST);
            }
            for (RoleEntity item : roleList) {
                roleMap.put(item.getId().toString(), item);
            }
        }
    }


    public void getUserMap(Map<String, UserEntity> userMap, Map<String, Object> params) throws XbbException{
        if(userMap.isEmpty()){
            List<UserEntity> userList = userModel.findEntitys(params);
            if(userList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.USER_NOT_EXIST);
            }
            for (UserEntity item : userList) {
                userMap.put(item.getUserId(), item);
            }
        }
    }

    public void getDepartmentMap(Map<String, DepartmentEntity> departmentMap, Map<String, Object> params) throws XbbException {
        if(departmentMap.isEmpty()) {
            List<DepartmentEntity> departmentList = departmentModel.findEntitys(params);
            if(departmentList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.DEPT_NOT_EXIST);
            }
            for (DepartmentEntity item : departmentList) {
                departmentMap.put(item.getId().toString(), item);
            }
        }
    }
    /**
     * 获取用户名称
     * @param userId
     * @return
     */
    public UserEntity getUserName(String userId, Map<String, UserEntity> userMap){
        return userMap.get(userId);
    }

    /**
     * 获取部门名称
     * @param departmentId
     * @return
     */
    public DepartmentEntity getDepartmentName(String departmentId, Map<String, DepartmentEntity> departmentMap){
        return departmentMap.get(departmentId);
    }

    /**
     * 获取角色名称
     * @param roleId
     * @return
     */
    public RoleEntity getRoleName(String roleId, Map<String, RoleEntity> roleMap){
        return roleMap.get(roleId);
    }

    public static VisibleRulePoJo getDefaultRule(RoleEnum roleEnum) {
        VisibleRulePoJo visibleRulePoJo = new VisibleRulePoJo();
        visibleRulePoJo.setRelative(Arrays.asList(RelatedPersonnelEnum.CREATOR.getType(), RelatedPersonnelEnum.OWNER.getType(), RelatedPersonnelEnum.OWNER_SUP.getType()));
        visibleRulePoJo.setType(VisibleTypeEnum.SOME_PEOPLE_CAN_SEE.getType());
        visibleRulePoJo.setRole(Arrays.asList(RoleEnum.ADMIN.getCode(),RoleEnum.BOSS.getCode(), roleEnum.getCode()));
        return visibleRulePoJo;
    }

    /**
     * 负责更新时校验处理
     * @param dataIdList 业务数据idList
     * @param corpid 公司id
     * @param businessType 业务类型
     * @param isPublic 是否公海(有个前负责人逻辑
     * @param mainUserIdMap 负责人map
     * @param coUserIdMap 协同人map
     */
    public void getUserIdMap(List<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic, Map<Long, List<String>> mainUserIdMap, Map<Long, List<String>> coUserIdMap) {
        List<UserTeamEntity> userTeamEntityList = businessUserTeamHelp.getUserTeamList(dataIdList, corpid, businessType, isPublic);

        List<String> delUserIdList = userModel.getDelUserIds(corpid);
        for (UserTeamEntity entity : userTeamEntityList) {
            if (delUserIdList.contains(entity.getUserId()) && !isPublic) {
                continue;
            }
            if (Objects.equals(entity.getIsMain(),1)){
                if (mainUserIdMap.containsKey(entity.getDataId())) {
                    List<String> userId =  mainUserIdMap.get(entity.getDataId());
                    userId.add(entity.getUserId());
                    mainUserIdMap.put(entity.getDataId(), userId);
                } else {
                    List<String> userId = new ArrayList<>();
                    userId.add(entity.getUserId());
                    mainUserIdMap.put(entity.getDataId(), userId);
                }

            }else {
                if (coUserIdMap.containsKey(entity.getDataId())) {
                    List<String> userId =  coUserIdMap.get(entity.getDataId());
                    userId.add(entity.getUserId());
                    coUserIdMap.put(entity.getDataId(), userId);
                }else {
                    List<String> userId = new ArrayList<>();
                    userId.add(entity.getUserId());
                    coUserIdMap.put(entity.getDataId(), userId);
                }
            }
        }
    }

    public Map<Long, List<String>> coUserMap(CoUserListDTO coUserListDTO) throws XbbException {
        Map<Long, List<String>> coUserMap;
        try {
            Map<String, Object> map = BeanUtil.convertBean2Map(coUserListDTO);
            List<PaasCoUserEntity> list = paasCoUserModel.list(map);
            if(list == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            coUserMap = new HashMap<>(list.size());
            list.forEach(item->{
                if (coUserMap.containsKey(item.getFormDataId())) {
                    List<String> userList = coUserMap.get(item.getFormDataId());
                    userList.add(item.getCoUserId());
                    coUserMap.put(item.getFormDataId(), userList);
                } else {
                    List<String> userList = new ArrayList<>();
                    userList.add(item.getCoUserId());
                    coUserMap.put(item.getFormDataId(), userList);
                }
            });
        } catch (XbbException e) {
            throw e;
        }  catch (Exception e) {
            LOG.error("coUser.coUserMap出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return coUserMap;
    }
}
